/*
 *
 * *******************************************************************
 *   @项目名称: BHex Android
 *   @文件名称: RateAndLocalManager.java
 *   @Date: 11/29/18 3:21 PM
 *   @Author: chenjun
 *   @Copyright（C）: 2018 BlueHelix Inc.   All rights reserved.
 *   注意：本内容仅限于内部传阅，禁止外泄以及用于其他的商业目的.
 *  *******************************************************************
 *
 */

package io.bhex.sdk.data_manager;

import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.os.LocaleList;
import android.util.DisplayMetrics;
import android.util.Log;

import java.util.Arrays;
import java.util.List;
import java.util.Locale;

import io.bhex.baselib.R;
import io.bhex.baselib.core.CApplication;
import io.bhex.baselib.core.Preferences;

public class RateAndLocalManager {
    public enum RateKind {
        CNY("CNY", CApplication.getMBaseContext().getString(R.string.string_cny),"¥"),
        USD("USD", CApplication.getMBaseContext().getString(R.string.string_usd),"$"),
        KRW("KRW", CApplication.getMBaseContext().getString(R.string.string_krw),"₩"),
        JPY("JPY", CApplication.getMBaseContext().getString(R.string.string_jpy),"¥"),
        VND("VND", CApplication.getMBaseContext().getString(R.string.string_vnd),"₫");


        public String code;
        public String name;
        public String symbol;
        public String priceToUSD;

        RateKind(String code, String name, String symbol) {
            this.code = code;
            this.name = name;
            this.symbol = symbol;
        }

        public static void setRateLocaKind(){
            CNY.name = mContext.getString(R.string.string_cny);
            USD.name = mContext.getString(R.string.string_usd);
            KRW.name = mContext.getString(R.string.string_krw);
            JPY.name = mContext.getString(R.string.string_jpy);
            VND.name = mContext.getString(R.string.string_vnd);
        }
    }

    //TODO 增加语言要修改的地方 1
    public enum LocalKind {
        /*zh("zh", CApplication.getInstance().getString(R.string.string_simple_chinese)),
        en("en", CApplication.getInstance().getString(R.string.string_english)),
        ko("ko", CApplication.getInstance().getString(R.string.string_korean)),
        vi("vi", CApplication.getInstance().getString(R.string.string_vietnamese)),
        ja("ja", CApplication.getInstance().getString(R.string.string_japanese)),
        tr("tr", CApplication.getInstance().getString(R.string.string_turkish));*/
        zh("zh", "简体中文"),
        en("en", "English"),
        ko("ko", "한국어"),
        vi("vi", "Tiếng Việt"),
        ja("ja", "日本語"),
        tr("tr", "Türkçe");
        public String code;
        public String name;

        LocalKind(String code, String name) {
            this.code = code;
            this.name = name;
        }
    }

    private RateKind mCurRateKind;
    private LocalKind mCurLocalKind;

    private static volatile RateAndLocalManager mInstance;
    public  static  Context mContext;
    private SharedPreferences mPrefs;
    private static SharedPreferences.Editor mEditor;
    private boolean mBNewest = false;

    public static final String PREFERENCE_CURLOCAL = "curLocal";
    public static final String PREFERENCE_CURRATE = "curRate";



    public static RateAndLocalManager GetInstance(Context context){
        if(mInstance == null){
            synchronized (RateAndLocalManager.class){
                if(mInstance==null){
                    mInstance = new RateAndLocalManager(context);
                }
            }
        }
        return mInstance;

    }

    /**
     * 获取汇率的请求参数
     * @return
     */
    public String getRatesReq(){
        RateKind[] mRates = RateKind.values();
        if (mRates == null) {
            return "";
        }
        List<RateKind> datas = Arrays.asList(mRates);
        StringBuffer stringBuffer = new StringBuffer();
        if (datas != null && datas.size() > 0) {
            for (RateKind rateKind : datas) {

                String rateCode = rateKind.code;
                if (stringBuffer.toString().length() > 0) {
                    stringBuffer.append("," + rateCode);
                } else {
                    stringBuffer.append(rateCode);
                }
            }

        }
        return stringBuffer.toString();

    }

    public RateKind getCurRateKind(){
        return mCurRateKind;
    }

    public LocalKind getCurLocalKind(){
        return mCurLocalKind;
    }

    //TODO 增加语言要修改的地方 2
    public String getCurLocalLanguage(){
        if(mCurLocalKind.code.equalsIgnoreCase("zh"))
            return "zh-CN";
        else if (mCurLocalKind.code.equalsIgnoreCase("en"))
            return "en-US";
        else if (mCurLocalKind.code.equalsIgnoreCase("ko"))
//            return "ko";
            return "ko-kr";
        else if (mCurLocalKind.code.equalsIgnoreCase("vi"))
//            return "vi-rVN";
            return "vi-VN";
        else if (mCurLocalKind.code.equalsIgnoreCase("ja"))
            return "ja-jp";
        else if (mCurLocalKind.code.equalsIgnoreCase("tr"))
            return "tr";
        else
            return "en-US";
    }

    private RateAndLocalManager(Context context){
        mContext = context;
        mPrefs = Preferences.getInstance(context).getSharePref();
        mEditor = mPrefs.edit();
        intLocal();
        initRate();
        //RateDataManager.GetInstance().InitRateData();
    }

    private void initxx(Context context){

    }

    //TODO 增加语言要修改的地方 3
    private void intLocal() {
        String prefLocal = mPrefs.getString(PREFERENCE_CURLOCAL, "");
        if(prefLocal.isEmpty())
        {
            String local = getLangLocalConfig();
            if(local.equalsIgnoreCase(LocalKind.zh.name()) || local.contains("zh")) {
                mCurLocalKind = LocalKind.zh;
            }else if(local.equalsIgnoreCase(LocalKind.ko.name())){
                mCurLocalKind = LocalKind.ko;
            }else if(local.equalsIgnoreCase(LocalKind.vi.name())){
                mCurLocalKind = LocalKind.vi;
            }else if(local.equalsIgnoreCase(LocalKind.ja.name())){
                mCurLocalKind = LocalKind.ja;
            }else if(local.equalsIgnoreCase(LocalKind.tr.name())){
                mCurLocalKind = LocalKind.tr;
            }else {
                mCurLocalKind = LocalKind.en;
            }
        }else{
            mCurLocalKind = LocalKind.valueOf(prefLocal);
        }
        //setLangLocal(mContext,mCurLocalKind.code);
    }

    private void initRate() {
        String prefRate = mPrefs.getString(PREFERENCE_CURRATE, "");
        if(prefRate.isEmpty())
        {
            switch (mCurLocalKind){
                case zh:
                    mCurRateKind = RateKind.CNY;
                    break;
                case en:
                    mCurRateKind = RateKind.USD;
                    break;
                case ko:
                    mCurRateKind = RateKind.KRW;
                    break;
                case ja:
                    mCurRateKind = RateKind.JPY;
                    break;
                case vi:
                    mCurRateKind = RateKind.VND;
                    break;
                default:
                    mCurRateKind = RateKind.USD;
            }
        }
        else
            mCurRateKind = RateKind.valueOf(prefRate);
    }

    public void setCurRateKind(RateKind rateKind){
        mCurRateKind = rateKind;
        //SharedPreferences.Editor prefEditor = mPrefs.edit();
        mEditor.putString(PREFERENCE_CURRATE, mCurRateKind.name());
        mEditor.apply();
    }

    public void SetCurLocalKind(Context context, LocalKind localKind){
        mCurLocalKind = localKind;
        setLangLocal(context, mCurLocalKind.code);
        setLangLocal(mContext, mCurLocalKind.code);
        RateKind.setRateLocaKind();
        //SharedPreferences.Editor prefEditor = mPrefs.edit();
        mEditor.putString(PREFERENCE_CURLOCAL, mCurLocalKind.name());
        mEditor.apply();
    }

    public void initRateKind(Context context){
        mContext = context;
        RateKind.setRateLocaKind();
    }

    public void SetCurLocalKindExt(Context context, LocalKind localKind){
        mCurLocalKind = localKind;
        mEditor.putString(PREFERENCE_CURLOCAL, mCurLocalKind.name());
        mEditor.apply();
    }

    public static String getStringById(int id) {
        String string ;
        //Resources resources = CApplication.getInstance().getResources();
        Resources resources = CApplication.getMBaseContext().getResources();
        String lang = RateAndLocalManager.GetInstance(CApplication.getInstance()).getCurLocalKind().code;
        if (!lang.isEmpty()){
            String raw = resources.getString(id);
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                Locale locale= resources.getConfiguration().getLocales().get(0);
                String.format(locale, raw,lang);
            }

            string = resources.getString(id,lang);
        }else {
            string = resources.getString(id,"");
        }

        if (string != null && string.length() > 0) {
            return string;
        }
        return "";
    }


    @TargetApi(Build.VERSION_CODES.N)
    public static Context wrapContext(Context context) {
        Resources resources = context.getResources();
        Locale locale = RateAndLocalManager.getSetLocale();
        //Locale locale = new String(RateAndLocalManager.getSetLanguageLocale(context));
        //Log.d("RateAndLocalManager","locale:"+locale.getLanguage());

        Configuration configuration = resources.getConfiguration();
        configuration.setLocale(locale);
        LocaleList localeList = new LocaleList(locale);
        LocaleList.setDefault(localeList);
        configuration.setLocales(localeList);
        return context.createConfigurationContext(configuration);
    }

    public static Locale getSetLocale() {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return Resources.getSystem().getConfiguration().getLocales().get(0);//解决了获取系统默认错误的问题
        } else {
            return Locale.getDefault();
        }

    }

    private void setLangLocal(Context context, String langLocal){
        Locale locale = new Locale(langLocal);


        Resources resources = context.getResources();
        if (resources==null)
            return;
        if(langLocal.equalsIgnoreCase(getLangLocalConfig(context)))
            return;


        DisplayMetrics dm = resources.getDisplayMetrics();
        Configuration config = resources.getConfiguration();

        if (config==null)
            return;

        //Locale locale = getSetLocale();


        //Build.VERSION_CODES.N == 24
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            config.setLocale(locale);
            LocaleList localeList = new LocaleList(locale);
            LocaleList.setDefault(localeList);
            config.setLocales(localeList);
        }
        else if (Build.VERSION.SDK_INT >= 17) {//Build.VERSION_CODES.JELLY_BEAN_MR1 == 17
            config.setLocale(locale);
            Locale.setDefault(locale);
            config.setLayoutDirection(locale);
        } else {
            config.locale = locale;
        }

        resources.updateConfiguration(config,dm);
    }

    private String getLangLocalConfig(){

        Configuration conf = mContext.getResources().getConfiguration();

        return conf.locale.getLanguage();
    }

    public String getLangLocalConfig(Context context){
        Configuration conf = context.getResources().getConfiguration();

        return conf.locale.getLanguage();
    }

    private static String getSetLanguageLocale(Context context) {
        RateAndLocalManager.LocalKind localKind = RateAndLocalManager.GetInstance(context).getCurLocalKind();
        if(localKind.code.equalsIgnoreCase("zh")){
            return "zh-CN";
        }else if(localKind.code.equalsIgnoreCase("en")){
            return "en-US";
        }else if(localKind.code.equalsIgnoreCase("ko")){
            return "ko-kr";
        } else if(localKind.code.equalsIgnoreCase("vi")){
            return "vi-VN";
        }else if(localKind.code.equalsIgnoreCase("ja")){
            return "ja-jp";
        }else if(localKind.code.equalsIgnoreCase("tr")){
            return "tr";
        }else{
            return "en-US";
        }
    }

}
